package com.salud.mendoza;

import java.sql.*;

/**
 * Created by ricardo on 09/06/14.
 */
public class MySQLManager {
    private static Object driver;
    private static Connection conn;
    private static MySQLManager mySQLManager;

    private MySQLManager() {
    }

    public static MySQLManager getInstance() {
        if (mySQLManager == null) {
            mySQLManager = new MySQLManager();
        }
        return mySQLManager;
    }

    private void loadDriver() {
        if (driver == null) {
            try {
                driver = Class.forName("com.mysql.jdbc.Driver").newInstance();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    private Connection getConnection() {
        loadDriver();
        try {
            if (conn == null || !conn.isClosed()) {
                try {
                    conn = DriverManager.getConnection("jdbc:mysql://192.168.0.9/global_2010?" +
                            "user=root&password=banana");

                } catch (SQLException ex) {
                    // handle any errors
                    System.out.println("SQLException: " + ex.getMessage());
                    System.out.println("SQLState: " + ex.getSQLState());
                    System.out.println("VendorError: " + ex.getErrorCode());
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public ResultSet consultar(String sql) {
        Connection connection = getConnection();
        ResultSet resultSet = null;
        try {
            Statement statement = connection.createStatement();
            if (statement.execute(sql)) {
                resultSet = statement.getResultSet();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;
    }
}
